import template from '../database/views/form_select.tpl.html'

const source = (utils, http, dialog, api) => {
	// function checkbox(obj, name, item, key) {
	// 	var _checked = obj[name] || [];
	// 	var keys = _checked.map(function(_item) {
	// 			return _item[key];
	// 		});
	// 	if (item.checked) {
	// 		if (keys.indexOf(item[key]) == -1) _checked.push(item);
	// 	} else {
	// 		var i = keys.indexOf(item[key]);
	// 		if (i > -1) _checked.splice(i, 1);
	// 	}
	// 	obj[name] = _checked;
	// }
	// function isChecked(obj, name, item, key) {
	// 	var _checked = obj[name] || [];
	// 	var keys = _checked.map(function(_item) {
	// 			return _item[key].toString();
	// 		});
	// 	return keys.length && keys.indexOf(item[key].toString()) > -1
	// }
	function checkbox(obj, name, checked, value) {
        var field = obj[name];
        field = field ? field.split(',') : [];
        value = value.toString();
        if (checked) {
            if (field.indexOf(value) == -1) field.push(value);
        } else {
            if (field.indexOf(value) > -1) field.splice(field.lastIndexOf(value), 1);
        }
        obj[name] = field.join(',');
    }
	let service = {
		dataSource: function() {
			var _loadData = function(scope, params) {
					scope = scope || this;
					params = params || {};
					return api.gridLoad({
						name: 'database',
						params: params,
						scope: scope,
						success: function(data, options) {
							var _scope = this;
							_scope.fields = angular.merge({}, _scope.fields, data.fields);
						}
					});
				};
				return api.form({
					title: '选择数据源',
					template,
					scope: {
						q: {},
						mapping: function(grid, row, col, field) {
							return api.mapping({
								grid: grid,
								row: row,
								col: col,
								field: field,
								scope: this
							});
						},
						add: function() {
							api.form({
								title: '添加数据源', 
								template: require('../database/views/form.tpl.html'),
								name: 'database_add',
								scope:{
									connTypes: utils.toArray(this.fields.connType)
								}
							}).then(function() {
								query();
							});
						},
						gridOptions: {
							paginationCurrentPage: api.page.pageNumber,
							paginationPageSize: api.page.pageSize,
							useExternalPagination: true,
							multiSelect: false,
							columns: [{
								name: '序号',
								width: 50,
								cellTemplate: '<div class="x-grid-inner">{{(grid.options.paginationCurrentPage - 1) * grid.options.paginationPageSize + (index + 1)}}</div>'
							}, {
								name: '数据源名称',
								width: 100,
								field: 'name'
							}, {
								name: '数据库名称',
								width: 100,
								field: 'dbName'
							}, {
								name: '数据库驱动',
								width: 100,
								field: 'connType',
								cellTemplate: '<div class="x-grid-inner" ng-bind-html="grid.appScope.mapping(grid, row, col)"></div>'
							}, {
								name: '数据库连接串',
								width: 200,
								field: 'jdbcUrl'
							}, {
								name: '用户名',
								width: 100,
								field: 'userName'
							}, {
								name: '状态',
								width: 100,
								field: 'isEnable',
								cellTemplate: '<div class="x-grid-inner" ng-bind-html="grid.appScope.mapping(grid, row, col)"></div>'
							}, {
								name: '操作',
								width: 100,
								field: 'jdbcUrl',
								cellTemplate: '<div class="x-grid-inner"><span class="btn-text"  ng-click="grid.appScope.testConn(row)">测试连接</span></div>'
							}],
							onRegisterApi: function(api, grid) {
								var _scope = grid.appScope;
								_scope.api = api;

								api.pagination && api.pagination.on.paginationChanged(_scope, function(newPage, pageSize) {
									_scope.query(false);
								});
							}
						},
						query: function(resetPage) {
							if (resetPage === false || this.gridOptions.paginationCurrentPage == 1) {
								_loadData(this, this.q);
							} else {
								api.gridReset(null, this);
							}
						}
					},
					name: 'database_filter',
					beforeSubmit: function(data) {
						var id = api.getGridSelectedId(this);
						if (!id) {
							dialog.alert('请选择数据源！');
							return false;
						}
						data.id = id;
					},
					resolveApply: false,
					resolveWait: function() {
						return _loadData(this);
					},
					config: {
						size: 960
					}
				});
		},
		dataTable: function(params) {
			return api.form({
				title: '选择源表',
				template: require('./views/form_tables.tpl.html'),
				name: 'database_tables_filter',
				scope: {
					checkbox
				},
				resolveWait: {
					tables: function() {
						return http.post({
							name: 'database_tables',
							params
						})
					}
				},
				resolveApplyScope: true,
				config: {
					windowClass: 'x-window',
					width: 520
				}
			});
		},
		localTable: function() {
			var loadData = function(_scope, params) {
				_scope = _scope || this;
				var node = _scope.selectedTreeNode;
				if (!node) {
					return;
				}
				params = params || {};
				angular.extend(params, {
					id: node.id
				});
				return api.gridLoad({
					name: 'task_local_tables',
					params: params,
					scope: _scope
				});
			};
			return api.form({
				title: '选择目标表',
				template: require('./views/form_local_tables.tpl.html'),
				name: 'task_local_table',
				beforeSettings: function() {
					var _scope = this;
					api.tree({
						scope: _scope,
						type: 'tree',
						url: 'tree.json'
					});
					_scope.changeNode = function(node) {
						_scope.selectedTreeNode = node;
						_scope.query();
					}
				},
				beforeSubmit: function(data, deferred) {
					var id = api.getGridSelectedId(this);
					if (!id) {
						dialog.alert('请选择虚拟表！');
						return false;
					}
					data.id = id;
				},
				scope: {
					q: {},
					query: function(resetPage) {
						var _scope = this;
						if (resetPage === false || _scope.gridOptions.paginationCurrentPage == 1) {
							loadData(_scope, _scope.q);
						} else {
							api.gridReset(null, _scope);
						}
					},
					gridOptions: {
						paginationCurrentPage: api.page.pageNumber,
						paginationPageSize: api.page.pageSize,
						useExternalPagination: true,
						multiSelect: false,
						columns: [{
							name: '表名',
							width: 200,
							field: 'name'
						}, {
							name: '注册时间',
							width: 200,
							field: 'date'
						}],
						forceFit: false,
						onRegisterApi: function(api, grid) {
							var _scope = grid.appScope;
							_scope.api = api;

							api.pagination && api.pagination.on.paginationChanged(_scope, function(newPage, pageSize) {
								_scope.query(false);
							});
						}
					}
				},
				config: {
					windowClass: 'x-window x-window-selection',
					width: '60%'
				}
			});
		}
	}
	return service;
}

source.$inject = ['ui.utils', 'ui.http', 'ui.dialog', 'ui.api'];

export default source;